package com.wk.controller.teacher;

import com.wk.pojo.User;
import com.wk.pojo.User_image_dto;
import com.wk.service.Userinfoservice;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: thesis
 * @description: 老师注册功能
 * @author: 王侃
 * @create: 2020-02-14 18:00
 **/
@Controller
public class Tearegistercontroller {
    @Autowired
    Userinfoservice userinfoservice;

    //接受Date类型数据
    @InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    //进行注册，将数据存入数据库
    @RequestMapping("/tea_registersubmit")
    public String registersubmit(User user, MultipartFile images) throws IOException, MessagingException {
        //赋予初值
        user.setStatus(0);
        user.setScore(0);
        user.setRole("tea");

        //发送邮件，并且用异步处理
        userinfoservice.sendemail(user.getEmail(),user.getUsername(),user.getPassword());

        //进行Md5加密，第一个参数为密码，第二参数是以用户名为盐，第三个参数是加密的次数
        Md5Hash md5registepassword=new Md5Hash( user.getPassword(), user.getUsername(),5);
        user.setPassword(md5registepassword.toString());

        //先存入数据库
        userinfoservice.insertintouser(user);
        //再通过新注册的用户获得他的id，这里不用用户名储存是因为如果删除后就会出现问题
        User user1=userinfoservice.selectbyusername(user.getUsername());
        Integer user1_id=user1.getId();

        //直接填写好路径，部署到服务器时再进行修改
        String path="D:\\thesis\\src\\main\\resources\\static\\icon";
        User_image_dto dto=new User_image_dto();
        //数据放入dto
        dto.setUser_id(user1_id);
        dto.setI_uploadpath(path);
        dto.setI_filename(images.getOriginalFilename());
        dto.setI_inputStream(images.getInputStream());

        userinfoservice.insertintoimages(dto);


        return "student/login";
    }
}
